var express = require('express');
var router = express.Router();
var usersDatas = require('../models/users_datas');
var encrypt = require('../tools/encrypt')
/**
 * status：
 * 500-数据库出错
 * 0-登陆失败
 * 1-登陆成功
 * 2-用户类型未知
 */
router.post("/", function (req, res, next) {
    let param = {
        // 获取request的数据内容
        username: req.body.username,
        password: encrypt(req.body.password),
        status: req.body.type,
    }
    //数据库申请
    usersDatas.findOne(param, function (err, doc) {
        if (err) {
            //数据库出错，登陆失败
            res.json({
                status: '500',
                msg: err.message,
                result: {}
            });
        } else if (req.body.type != 1 && req.body.type != 0) {
            res.json({
                status: "2",
                msg: "未定义用户类型！",
                result: {}
            });
        } else {
            //数据库查询成功
            if (doc) {
                //找到匹配数据
                //将数据写入cookie和session
                res.cookie("userId", doc.username, {
                    path: '/',
                    maxAge: 1000 * 60 * 60 * 168,
                });
                req.session.user = doc;
                //console.log(doc)
                //req.session.userState=1;
                res.json({
                    status: "1",
                    msg: '',
                    result: {
                        username: doc.username,
                        type:doc.status,
                        userid:doc._id
                    }
                });
            } else {
                //用户数据未匹配，登陆失败
                res.json({
                    status: "0",
                    msg: "not found",
                    result: {}
                });
            }
        }

    })
})
//测试使用，用过localhost::3000/reqLogin输出数据库信息
router.get("/", function (req, res, next) {
    usersDatas.find({}, function (err, doc) {
        if (err) {
            res.json({
                status: "500",
                msg: err.message
            })
        } else {
            res.json({
                status: '1',
                msg: "",
                result: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
})
router.get('/login', function (req, res, next) {
    res.render('login')
})
module.exports = router;